import asyncio
import functools
import os
import time
from concurrent.futures import ThreadPoolExecutor
from async_threading import async_timed
import requests


def get_status_code(url):
    response = requests.get(url)
    return response.status_code


@async_timed()
async def main():
    # loop = asyncio.get_running_loop()
    # urls = ["http://www.baidu.com" for _ in range(100)]
    # # 默认执行器始终默认为 ThreadPoolExecutor , 使用None代替
    # tasks = [loop.run_in_executor(None, functools.partial(get_status_code, url)) for url in urls]
    # result = await asyncio.gather(*tasks)
    # print(result)

    # 简化一下：使用 to_thread 协程消除了使用functions.partial以及对asyncio.get_running_loop的调用
    urls = ["http://www.baidu.com" for _ in range(100)]
    tasks = [asyncio.to_thread(get_status_code, url) for url in urls]
    result = await asyncio.gather(*tasks)
    print(result)
asyncio.run(main())
